#include"DList.h"
ListNode* ListInit(ListNode* phead)
{
	// ListNode* NewNode = (ListNode*)malloc(sizeof(ListNode) * 1);
	ListNode* NewNode = CreateNode(0);
	NewNode->prev = NewNode;
	NewNode->next = NewNode;
	phead = NewNode;
	return phead;
}

ListNode* CreateNode(DataType x)
{
	ListNode* NewNode = (ListNode*)malloc(sizeof(ListNode));
	if (NewNode==NULL)
	{
		printf("CreateNode fail!!!!\n");
		exit(-1);
	}
	NewNode->data = x;
	NewNode->prev = NULL;
	NewNode->next = NULL;
	return NewNode;
}
void ListPushBack(ListNode* phead, DataType val)
{
	assert(phead);
	// ListNode* NewNode = (ListNode*)malloc(sizeof(ListNode) * 1);
	//ListNode* NewNode = CreateNode(val);
	//NewNode->data = val;
	//ListNode* tail = phead->prev;

	//tail->next = NewNode;
	//NewNode->prev = tail;
	//phead->prev = NewNode;
	//NewNode->next = phead;

	ListInsert(phead, val);
}
void ListPrint(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d => ", cur->data);
		cur = cur->next;
	}
	printf("=> NULL\n");
}

void ListPopBack(ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	ListNode* tail = phead->prev;
	ListNode* prev = tail->prev;

	phead->prev = prev;
	prev->next = tail->next;

	free(tail);
}

void ListPushFront(ListNode* phead, DataType val)
{
	assert(phead);
	//ListNode* NewNode = CreateNode(val);
	//NewNode->data = val;
	//ListNode* NewNode_next = phead->next;
	//
	//NewNode->prev = phead;
	//phead->next = NewNode;

	//NewNode->next = NewNode_next;
	//NewNode_next->prev = NewNode;
	ListInsert(phead->next, val);
}

void ListdPopFront(ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	ListNode* cur = phead->next;
	ListNode* next = cur->next;
	free(cur);
	phead->next = next;
	next->prev = phead;
}

ListNode* ListFind(ListNode* phead, DataType x)
{
	ListNode* cur = phead->next;
	while (phead != cur)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, DataType x)
{
	ListNode* NewNode = CreateNode(x);
	ListNode* pos_prev = pos->prev;

	pos_prev->next = NewNode;
	NewNode->prev = pos_prev;

	NewNode->next = pos;
	pos->prev = NewNode;
}

void ListErease(ListNode* pos)
{
	ListNode* prev, * next;
	prev = pos->prev;
	next = pos->next;
	free(pos);
	prev->next = next;
	next->prev = prev;
}

void ListDistory(ListNode* phead)
{
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		ListNode* temp = cur->next;
		free(cur);
		cur = temp;
	}
	free(phead);
}